package org.lemon.transport.http.controller;

import org.lemon.transport.context.data.ota.OtaPackageType;
import org.lemon.transport.http.service.OtaPackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

@RestController
public class OtaPackageController {

    @Autowired
    private OtaPackageService otaPackageService;

    /**
     * 获取设备固件包
     *
     * @param deviceToken
     * @param title       fw_title
     * @param version     fw_version
     * @param size        下载块的大小, 可忽略, 下载整个文件
     * @param chunk       下载块的起始索引位置, 可忽略, 下载整个文件
     * @return
     */
    @GetMapping(value = "/api/v1/{deviceToken}/firmware")
    public DeferredResult<ResponseEntity<ByteArrayResource>> getFirmware(
            @PathVariable("deviceToken") String deviceToken,
            @RequestParam(value = "title") String title,
            @RequestParam(value = "version") String version,
            @RequestParam(value = "size", required = false, defaultValue = "0") int size,
            @RequestParam(value = "chunk", required = false, defaultValue = "0") int chunk) {

        return otaPackageService.getOtaPackage(deviceToken, title, version, size, chunk, OtaPackageType.FIRMWARE);
    }

    /**
     * 获取设备软件包
     *
     * @param deviceToken
     * @param title       sw_title
     * @param version     sw_version
     * @param size
     * @param chunk
     * @return
     */
    @GetMapping(value = "/api/v1/{deviceToken}/software")
    public DeferredResult<ResponseEntity<ByteArrayResource>> getSoftware(
            @PathVariable("deviceToken") String deviceToken,
            @RequestParam(value = "title") String title,
            @RequestParam(value = "version") String version,
            @RequestParam(value = "size", required = false, defaultValue = "0") int size,
            @RequestParam(value = "chunk", required = false, defaultValue = "0") int chunk) {

        return otaPackageService.getOtaPackage(deviceToken, title, version, size, chunk, OtaPackageType.FIRMWARE);
    }
}
